<template>
  <div class="equipment-manage-add-page">
    <div class="page-title-container flex" :title="pageTtile">
      <a-button type="default" @click="back()">返回 </a-button>
    </div>
    <div class="page-body-container">
      <!-- 顶部查询条件 -->
      <div class="conditions-warp">
        <a-row>
          <a-form-model ref="ruleForm" :model="conditions" :rules="rules">
            <!-- 项目名称 -->
            <a-col :xs="24" :sm="24" :md="24" :lg="12" :xl="12" :xxl="6">
              <a-form-model-item ref="proName" label="项目名称" prop="proName">
                <a-select
                  v-model="conditions.proName"
                  placeholder="请选择项目名称"
                  :loading="conditions.proNameLoading"
                  @change="conditionChange($event, 'proName')"
                >
                  <a-select-option
                    :value="item.tenantCode"
                    v-for="item in conditions.proNameSource"
                    :key="item.id"
                  >
                    {{ item.proName }}</a-select-option
                  >
                </a-select>
              </a-form-model-item>
            </a-col>
            <!-- 标段名称 -->
            <a-col :xs="24" :sm="24" :md="24" :lg="12" :xl="12" :xxl="6">
              <a-form-model-item
                ref="blockName"
                label="标段名称"
                prop="blockName"
              >
                <a-select
                  v-model="conditions.blockName"
                  placeholder="请选择标段名称"
                  :loading="conditions.blockLoading"
                  @change="conditionChange($event, 'blockName')"
                >
                  <a-select-option
                    :value="item.orgCode"
                    v-for="item in conditions.blockNameSource"
                    :key="item.orgCode"
                  >
                    {{ item.orgName }}</a-select-option
                  >
                </a-select>
              </a-form-model-item>
            </a-col>
            <!-- 角色名称 -->
            <a-col :xs="24" :sm="24" :md="24" :lg="12" :xl="12" :xxl="12">
              <a-form-model-item
                ref="roleName"
                label="角色名称"
                prop="roleName"
              >
                <a-select
                  mode="multiple"
                  v-model="conditions.roleName"
                  placeholder="请选择角色名称"
                  :loading="conditions.roleLoading"
                  @change="conditionChange($event, 'roleName')"
                >
                  <a-select-option
                    :value="item.id"
                    v-for="item in conditions.roleNameSource"
                    :key="item.roleCode"
                  >
                    {{ item.roleName }}
                  </a-select-option>
                </a-select>
              </a-form-model-item>
            </a-col>
            <!-- 系统名称 -->
            <a-col :xs="24" :sm="24" :md="24" :lg="12" :xl="12" :xxl="6">
              <a-form-model-item ref="sysName" label="系统名称" prop="sysName">
                <a-select
                  v-model="conditions.sysName"
                  placeholder="请选择系统名称"
                  :loading="conditions.sysNameLoading"
                  @change="conditionChange($event, 'sysName')"
                >
                  <a-select-option
                    :value="item.systemCode"
                    v-for="item in conditions.sysNameSource"
                    :key="item.systemCode"
                  >
                    {{ item.systemName }}</a-select-option
                  >
                </a-select>
              </a-form-model-item>
            </a-col>
            <!-- 设备类型 -->
            <a-col :xs="24" :sm="24" :md="24" :lg="12" :xl="12" :xxl="6">
              <a-form-model-item ref="equType" label="设备类型" prop="equType">
                <a-select
                  v-model="conditions.equType"
                  placeholder="请选择设备类型"
                  :loading="conditions.equTypeLoading"
                  @change="conditionChange($event, 'equType')"
                >
                  <a-select-option
                    :value="item.dicValue"
                    v-for="item in conditions.equTypeSource"
                    :key="item.dicValue"
                    >{{ item.dicDesc }}</a-select-option
                  >
                </a-select>
              </a-form-model-item>
            </a-col>
            <!-- 试验室名称  -->
            <a-col
              :xs="24"
              :sm="24"
              :md="24"
              :lg="12"
              :xl="12"
              :xxl="6"
              v-if="conditions.sysName == 'SYGLXT'"
            >
              <a-form-model-item
                ref="testName"
                label="试验室名称"
                prop="testName"
              >
                <a-select
                  v-model="conditions.testName"
                  placeholder="请选择试验室名称"
                  :loading="conditions.testNameLoading"
                  @change="conditionChange($event, 'testName')"
                >
                  <a-select-option
                    :value="item.orgCode"
                    v-for="item in conditions.testNameSource"
                    :key="item.orgCode"
                    >{{ item.orgName }}</a-select-option
                  >
                </a-select>
              </a-form-model-item>
            </a-col>
          </a-form-model>
        </a-row>
      </div>
      <!--  -->
      <div class="equment-list-card-container">
        <addEquCard
          :title="getEqumentName() + '（' + (index + 1) + '）'"
          :id="'id_' + index"
          :ref="'addEquCard_' + index"
          :fieldSource="fieldSource"
          :isShowDelete="index > 0"
          v-for="(item, index) in equimentList"
          :key="index"
          @handleDelete="addEquCardDelete($event, index)"
        ></addEquCard>
      </div>
      <!-- 添加设备 -->
      <div class="add-equment-button" @click="addEquiment()">+ 添加数据</div>
      <!-- 提交按钮 -->
      <div class="footer">
        <a-button @click="back()"> 取消 </a-button>
        <a-button
          type="primary"
          style="margin-left: 10px"
          :disabled="equimentList.length == 0"
          @click="onSubmit()"
        >
          确定
        </a-button>
      </div>
    </div>
  </div>
</template>

<script>
//【新增】页面
import addEquCard from "./components/addEquCard";
import {
  getProjectList,
  getBlockList,
  getSystemList,
  getEquTypeList,
  getByCondition,
  addEquiment,
  getTestNameList,
} from "@/api/user-center/equipmentManage.js";
import { getUserRole } from "@/api/user-center/userManage.js";
import { getLoginData } from "@/tools";
export default {
  components: { addEquCard },
  data() {
    return {
      pageTtile: "新增",
      operate: 0,
      conditions: {
        //项目名称
        proNameSource: [],
        proName: undefined,
        proNameLoading: true,
        //标段名称
        blockNameSource: [],
        blockName: undefined,
        blockLoading: false,
        //角色名称
        roleNameSource: [],
        roleName: undefined,
        roleLoading: false,
        //系统名称
        sysNameSource: [],
        sysName: undefined,
        sysNameLoading: false,
        //设备类型
        equTypeSource: [],
        equType: undefined,
        equTypeLoading: false,
        //实验室名称
        testNameLoading: false,
        testNameSource: [],
        testName: undefined,
      },
      rules: {
        proName: [
          { required: true, message: "请选择项目名称", trigger: "change" },
        ],
        blockName: [
          { required: true, message: "请选择标段名称", trigger: "change" },
        ],
        roleName: [
          { required: true, message: "请选择角色名称", trigger: "change" },
        ],
        sysName: [
          { required: true, message: "请选择系统名称", trigger: "change" },
        ],
        equType: [
          { required: true, message: "请选择设备类型", trigger: "change" },
        ],
        testName: [
          { required: true, message: "请选择试验室名称", trigger: "change" },
        ],
      },
      fieldSource: [],
      equimentList: [],
      equimentParamsList: [],
    };
  },
  mounted() {
    this.getProjectList();
  },
  methods: {
    //提交
    onSubmit() {
      let { equimentList } = this;
      if (equimentList.length == 0) {
        return this.$message.warn("最少添加一条数据");
      }
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          try {
            this.equimentParamsList = [];
            equimentList.forEach((_, index) => {
              let ref = this.$refs["addEquCard_" + index]?.[0];
              if (ref) {
                ref
                  .dataValidate()
                  .then((res) => {
                    let { form = {} } = res;
                    Object.keys(form).forEach((key) => {
                      if (form[key] == undefined) {
                        form[key] = "";
                      }
                    });
                    this.$set(
                      this.equimentParamsList,
                      this.equimentParamsList.length,
                      form
                    );
                  })
                  .catch((_) => {
                    let { title } = _;
                    this.isValidate = false;
                    this.$message.error(`【${title}】数据填写不完整`);
                    throw _;
                  });
              }
            });
            //开启异步线程
            setTimeout((_) => {
              if (this.equimentParamsList.length == this.equimentList.length) {
                //执行提交接口
                this.confirmAddEquiment();
              }
            });
          } catch (error) {}
        } else {
          let { roleName } = this.conditions;
          if (!roleName || roleName.length == 0) {
            this.$message.warn("请选择角色名称");
          }
          return false;
        }
      });
    },

    //确定
    confirmAddEquiment() {
      this.submitLoading = true;
      let {
        proName,
        blockName,
        sysName,
        equType,
        roleName = [],
      } = this.conditions;
      this.equimentParamsList.forEach((v) => {
        if (!v.long || !v.lat) {
          v.location = "";
        } else {
          v.location = `${v.long},${v.lat}`;
        }
        v.tenantCode = proName || "";
        if (this.conditions.sysName == "SYGLXT") {
          v.orgCode = this.conditions.testName;
        } else {
          v.orgCode = blockName || "";
        }

        v.systemCode = sysName || "";
        v.equTypeValue = equType || "";
        v.roleIds = roleName.toString();
      });
      addEquiment(this.equimentParamsList)
        .then((res) => {
          this.$message.success("操作成功");
          this.back();
        })
        .catch((_) => {
          this.$message.error("操作失败，请稍后重试！");
        })
        .finally((_) => {
          this.submitLoading = false;
        });
    },

    //添加数据
    addEquiment() {
      let { equType } = this.conditions;
      if (equType && this.fieldSource.length > 0) {
        this.equimentList.push({});
      } else {
        if (!equType) {
          return this.$message.warn("请先选择设备类型");
        } else {
          return this.$message.warn(`暂无【${this.getEqumentName()}】相关信息`);
        }
      }
    },

    //删除数据
    addEquCardDelete(ev, index) {
      let that = this;
      const h = this.$createElement;
      this.$confirm({
        title: "操作提示",
        content: `您确定删除【${
          this.getEqumentName() + "（" + (index + 1) + "）"
        }】吗?`,
        okText: "确定",
        okType: "primary",
        cancelText: "取消",
        centered: true,
        icon: () =>
          h("a-icon", {
            props: {
              type: "question-circle",
              theme: "filled",
            },
            style: "color:#FB5A5A",
          }),
        onOk() {
          that.equimentList = that.equimentList.filter((_, i) => i != index);
        },
        onCancel() {},
      });
    },

    //查询设备字段列表
    getByCondition() {
      return new Promise((resolve, reject) => {
        let { proName, blockName, sysName, equType } = this.conditions;
        getByCondition({
          tenantCode: proName || "",
          secCode: blockName || "",
          systemCode: sysName || "",
          equTypeValue: equType || "",
        })
          .then((res) => {
            let { data } = res;
            this.fieldSource = data?.result || [];
            //默认添加一个设备
            if (this.fieldSource.length > 0) {
              this.equimentList = [{}];
            }
          })
          .catch((_) => {
            this.fieldSource = [];
          });
      });
    },

    //【查询条件】监听查询条件切换
    conditionChange(ev, keyName) {
      this.conditions[keyName] = ev;
      switch (keyName) {
        case "proName":
          this.conditions.blockName = undefined;
          this.conditions.sysName = undefined;
          this.conditions.equType = undefined;
          this.conditions.blockNameSource = [];
          this.conditions.sysNameSource = [];
          this.conditions.equTypeSource = [];
          this.getBlockList(ev || "");
          this.getSystemList(ev || "");
          this.getEquTypeList(ev || "");
          break;

        case "blockName":
          this.getRoleList(ev || "");
          if (this.conditions.sysName == "SYGLXT") {
            this.getTestNameList();
          }
          break;

        case "sysName":
          this.conditions.equType = undefined;
          this.conditions.equTypeSource = [];
          this.getEquTypeList(ev || "");
          //查询实验室名称
          if (ev == "SYGLXT") {
            this.getTestNameList();
          }
          break;

        case "equType":
          this.getByCondition();
          break;

        default:
          break;
      }
    },

    //【查询条件】查询试验室名称
    getTestNameList() {
      this.conditions.testNameLoading = true;
      return new Promise((resolve, reject) => {
        let { userId } = getLoginData();
        getTestNameList({
          userId,
          tenantCode: this.conditions.proName,
          orgCode: this.conditions.blockName,
        })
          .then((res) => {
            let { data } = res;
            this.conditions.testNameSource = data?.result || [];
            resolve();
          })
          .catch((_) => {
            this.conditions.testNameSource = [];
            this.conditions.testName = undefined;
            reject();
          })
          .finally((_) => {
            this.conditions.testNameLoading = false;
          });
      });
    },

    //【查询条件】查询项目名称
    getProjectList() {
      this.conditions.proNameLoading = true;
      return new Promise((resolve, reject) => {
        let { userId } = getLoginData();
        getProjectList({ userId })
          .then((res) => {
            let { data } = res;
            this.conditions.proNameSource = data?.result || [];
            resolve();
          })
          .catch((_) => {
            this.conditions.proNameSource = [];
            reject();
          })
          .finally((_) => {
            this.conditions.proNameLoading = false;
          });
      });
    },

    //【查询条件】查询标段名称
    getBlockList(tCode = "") {
      this.conditions.blockLoading = true;
      return new Promise((resolve, reject) => {
        let { userId, tenantCode } = getLoginData();
        getBlockList({ userId, tenantCode: tCode })
          .then((res) => {
            let { data } = res;
            this.conditions.blockNameSource = data?.result || [];
            resolve();
          })
          .catch((_) => {
            this.conditions.blockNameSource = [];
            reject();
          })
          .finally((_) => {
            this.conditions.blockLoading = false;
          });
      });
    },

    //【查询条件】查询角色下拉框
    getRoleList(orgCode = "") {
      this.conditions.roleLoading = true;
      return new Promise((resolve, reject) => {
        getUserRole({ tenantCode: this.conditions.proName, orgCode })
          .then((res) => {
            let { data } = res;
            this.conditions.roleNameSource = data?.result || [];
            resolve();
          })
          .catch((_) => {
            this.conditions.roleNameSource = [];
            reject();
          })
          .finally((_) => {
            this.conditions.roleLoading = false;
          });
      });
    },

    //【查询条件】查询系统名称
    getSystemList(tCode = "") {
      this.conditions.sysNameLoading = true;
      return new Promise((resolve, reject) => {
        getSystemList({ tenantCode: tCode })
          .then((res) => {
            let { data } = res;
            this.conditions.sysNameSource = data?.result || [];
            resolve();
          })
          .catch((_) => {
            this.conditions.sysNameSource = [];
            reject();
          })
          .finally((_) => {
            this.conditions.sysNameLoading = false;
          });
      });
    },

    //【查询条件】查询设备类型
    getEquTypeList(systemCode = "") {
      this.conditions.equTypeLoading = true;
      return new Promise((resolve, reject) => {
        getEquTypeList({ systemCode })
          .then((res) => {
            let { data } = res;
            this.equimentList = [];
            this.conditions.equTypeSource = data?.result || [];
            resolve();
          })
          .catch((_) => {
            this.conditions.equTypeSource = [];
            reject();
          })
          .finally((_) => {
            this.conditions.equTypeLoading = false;
          });
      });
    },

    //获取设备名称
    getEqumentName() {
      let { equTypeSource, equType = "" } = this.conditions;
      if (equType) {
        return equTypeSource.find((v) => v.dicValue == equType)?.dicDesc || "";
      } else {
        return "";
      }
    },

    //返回
    back() {
      this.$router.back();
    },
  },
};
</script>

<style lang="less">
.equipment-manage-add-page {
  height: 100%;
  .flex();
  flex-direction: column;
  box-sizing: border-box;
  padding: 0 0 0 10px;
  .page-title-container {
    height: 46px;
    background: #ffffff;
    justify-content: space-between;
    padding: 0 20px;
    align-items: center;
    border-bottom: 1px solid #e8ebf0;
    &::before {
      .flex();
      align-items: center;
      content: attr(title);
      font-size: 16px;
      height: 16px;
      border-left: 3px solid var(--primary-color);
      padding-left: 10px;
    }
  }
  .page-body-container {
    flex: 1;
    flex-wrap: wrap;
    background: #fff;
    .custom-scrollbar();
    .conditions-warp {
      padding: 30px 100px 0 10px;
      .ant-form-item {
        .flex();
        .ant-form-item-label {
          width: 120px;
          flex-shrink: 0;
        }
        .ant-form-item-control-wrapper {
          flex: 1;
          textarea {
            height: 80px;
          }
          .ant-calendar-picker {
            width: 100%;
          }
        }
      }
      /deep/.ant-select {
        width: 100%;
      }
    }
    .equment-list-card-container {
      padding: 0 32px;
    }
    .add-equment-button {
      .flex();
      align-items: center;
      justify-content: center;
      height: 36px;
      background: rgba(55, 89, 160, 0.1);
      border: 1px dashed var(--primary-color);
      margin: 0 32px;
      cursor: pointer;
      color: var(--primary-color);
    }
    .footer {
      height: 72px;
      border-top: 1px solid #f3f4f6;
      margin-top: 34px;
      .flex();
      justify-content: center;
      align-items: center;
    }
  }
}
</style>
